<template>
  <div class="container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>新增旷寝记录</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <el-form ref="formRef" :model="absence" :rules="rules" label-width="120px" style="max-width: 800px;">
        <el-form-item label="学生" prop="studentId">
          <el-select
            v-model="absence.studentId"
            filterable
            placeholder="请选择学生"
            style="width: 100%"
            @change="handleStudentChange"
          >
            <el-option
              v-for="student in students"
              :key="student.studentId"
              :label="`${student.studentId} - ${student.name} (${student.dormBuildName} ${student.dormName})`"
              :value="student.studentId"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="absence.studentName" disabled />
        </el-form-item>
        
        <el-form-item label="宿舍楼" prop="dormBuildName">
          <el-input v-model="absence.dormBuildName" disabled />
        </el-form-item>
        
        <el-form-item label="宿舍号" prop="dormName">
          <el-input v-model="absence.dormName" disabled />
        </el-form-item>
        
        <el-form-item label="旷寝日期" prop="absenceDate">
          <el-date-picker
            v-model="absence.absenceDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="原因" prop="reason">
          <el-input
            v-model="absence.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入旷寝原因"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  data() {
    // 自定义日期验证函数
    const validateDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择旷寝日期'))
        return
      }
      
      const selectedDate = new Date(value)
      const today = new Date()
      today.setHours(0, 0, 0, 0) // 清除时间部分，只比较日期
      
      if (selectedDate > today) {
        callback(new Error('你不能预言未来'))
      } else {
        callback()
      }
    }
    
    return {
      absence: {
        studentId: null,
        studentName: '',
        dormBuildName: '',
        dormName: '',
        absenceDate: '',
        reason: ''
      },
      students: [],
      rules: {
        studentId: [
          { required: true, message: '请选择学生', trigger: 'change' }
        ],
        absenceDate: [
          { required: true, validator: validateDate, trigger: 'change' }
        ],
        reason: [
          { required: true, message: '你不能施加莫须有的罪名', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    await this.fetchStudents()
  },
  methods: {
    async fetchStudents() {
      try {
        const response = await axios.get(
          "http://localhost:8080/UserMgr_Web_exploded/students",
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        this.students = response.data
      } catch (error) {
        ElMessage.error('获取学生列表失败')
        console.error(error)
      }
    },
    handleStudentChange(studentId) {
      const selectedStudent = this.students.find(s => s.studentId === studentId)
      if (selectedStudent) {
        this.absence.studentName = selectedStudent.name
        this.absence.dormBuildName = selectedStudent.dormBuildName
        this.absence.dormName = selectedStudent.dormName
      }
    },
    async submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post(
              "http://localhost:8080/UserMgr_Web_exploded/absences", 
              this.absence,
              {
                headers: {
                  'Authorization': 'Bearer ' + localStorage.getItem('token')
                }
              }
            )
            
            if (response.data.success) {
              ElMessage.success('添加旷寝记录成功')
              this.$router.push('/absences')
            } else {
              ElMessage.error(response.data.message || '添加失败')
            }
          } catch (error) {
            ElMessage.error('添加旷寝记录失败')
            console.error(error)
          }
        }
      })
    },
    resetForm() {
      this.$refs.formRef.resetFields()
      this.absence = {
        studentId: null,
        studentName: '',
        dormBuildName: '',
        dormName: '',
        absenceDate: '',
        reason: ''
      }
    },
    goBack() {
      this.$router.push('/absences')
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>